/**
 * ble data handle
 */
#include <stdio.h>
#include <zephyr/kernel.h>
#include <zephyr/types.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/logging/log.h>

#include "ble_central.h"
#include "ble_peripheral.h"
#include "serial.h"
#include "pkt_codec.h"
#include "ble_types.h"
#include "ble_handler.h"

LOG_MODULE_REGISTER(ble, LOG_LEVEL_INF);

struct serial_inst *serial_inst;

static pkt_t decoder_pkt;
static decoder_ctx_t decoder_ctx;

static int serial_rx_proccess_func(uint8_t *data, uint16_t len)
{
    LOG_HEXDUMP_INF(data, len, "uart rx");
    for (int i = 0; i < len; i++)
    {
        if (pkt_decode(&decoder_ctx, data[i]))
        {
            pkt_t *p_pkt = decoder_ctx.current_packet;
            switch (p_pkt->cmd)
            {
                case BLE_CMD_SCAN_START:
                    ble_scan_start_rsp(p_pkt->data, p_pkt->data_len);
                    break;

                case BLE_CMD_SCAN_STOP:
                    ble_scan_stop_rsp(p_pkt->data, p_pkt->data_len);
                    break;

                case BLE_CMD_CONNECT:
                    /* code */
                    break;

                case BLE_CMD_DISCONNECT:
                    /* code */
                    break;

                default:
                    break;
            }
        }
    }
    return 0;
}

int ble_init(void)
{
    int err;

    err = bt_enable(NULL);
    if (err)
    {
        printk("Bluetooth init failed (err %d)\n", err);
        return -1;
    }

    printk("Bluetooth initialized\n");

    err |= ble_peripheral_init();
    k_msleep(1000);
    err |= ble_central_init();

    // init decoder
    pkt_decode_init(&decoder_ctx, &decoder_pkt);

    // serial init
    serial_inst = serial_init((serial_rx_proccess_t)serial_rx_proccess_func);
    if (!serial_inst)
    {
        printk("Failed to init serial.\n");
        return -1;
    }

    return err;
}
